package com.tms.quartz.service.impl;

import com.tms.domain.Tool;
import com.tms.quartz.job.MailJob;
import com.tms.quartz.job.SimpleJob;
import com.tms.quartz.service.JobService;
import com.tms.quartz.service.QuartzService;
import com.tms.quartz.service.TriggerService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

/**
 * @author jackie
 * @date 2020年6月30日
 */
@Service
public class QuartzServiceImpl implements QuartzService {

    @Autowired
    Scheduler scheduler;

    @Autowired
    JobService jobService;

    @Autowired
    TriggerService triggerService;

    private final String PAUSE = "pause";

    private final String RESUME = "resume";

    private final String REMOVE = "remove";

    /**
     * 添加job并与trigger绑定
     *
     * @param tool 需要添加的job
     * @param type job类型
     * @param date trigger的循环日期
     * @param map  job的参数
     * @return 成功返回true，失败返回false
     * @throws SchedulerException scheduler异常
     */
    @Override
    public boolean addJobToTrigger(Tool tool, int type, int date, Map<String, String> map) throws SchedulerException {
        // 启动调度器
        scheduler.start();
        String triggerName;
        String triggerGroup;
        String jobName;
        String jobGroup;
        if (type == 1) {
            triggerName = String.valueOf(tool.gettDef().getWorkcell().getId());
            triggerGroup = String.valueOf(tool.getId());
        } else {
            triggerName = String.valueOf(tool.getId());
            triggerGroup = String.valueOf(tool.gettDef().getOwner().getId());
        }
        TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroup);
        try {
            JobDetail jobDetail;
            CronTrigger trigger;
            //取得trigger，如果没有则新建
            if (scheduler.checkExists(triggerKey)) {
                trigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            } else {
                String cron = "0 0 0 " + date + " * ?";
                //String cron = "0 * * * * ?";
                trigger = triggerService.addTrigger(triggerName, triggerGroup, cron, null);
            }
            //取得或者新建失败
            if (trigger == null) {
                return false;
            }
            //根据不同的job类型选择不同的class
            if (type == 1) {
                jobName = String.valueOf(tool.getId());
                jobGroup = String.valueOf(tool.gettDef().getOwner().getId());
                jobDetail = jobService.addJob(SimpleJob.class, jobName, jobGroup, map);
            } else {
                jobGroup = String.valueOf(tool.getId());
                jobName = String.valueOf(tool.gettDef().getOwner().getId());
                jobDetail = jobService.addJob(MailJob.class, jobName, jobGroup, map);
            }
            //新建jobDetail成功则加入到trigger
            if (jobDetail != null) {
                scheduler.scheduleJob(jobDetail, trigger);
                return true;
            } else {
                return false;
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 对job进行操作
     *
     * @param tool job对应的tool
     * @param type job类型
     * @param type1 操作类型
     * @return 成功返回true，失败返回false
     * @throws SchedulerException scheduler异常
     */
    @Override
    public boolean handerJob(Tool tool, int type, String type1) throws SchedulerException {
        String jobName;
        String jobGroup;
        //根据不同job类型取得不同的name以及group
        if (type == 1) {
            jobName = String.valueOf(tool.getId());
            jobGroup = String.valueOf(tool.gettDef().getOwner().getId());
        } else {
            jobGroup = String.valueOf(tool.getId());
            jobName = String.valueOf(tool.gettDef().getOwner().getId());
        }
        switch (type1) {
            case PAUSE:
                return jobService.pauseJob(jobName, jobGroup);
            case RESUME:
                return jobService.resumeJob(jobName, jobGroup);
            case REMOVE:
                return jobService.removeJob(jobName, jobGroup);
            default:
                return false;
        }
    }

    /**
     * 修改tool对应的触发器的cron表达式
     *
     * @param tool  触发器名称和分组
     * @param cycle 修改的循环天数
     * @return 成功返回true，失败返回false
     * @throws SchedulerException
     */
    @Override
    public boolean changeCycle(Tool tool, int cycle) throws SchedulerException {
        String triggerName = String.valueOf(tool.getTDef().getWorkcell().getId());
        String triggerGroup = String.valueOf(tool.getId());
        TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroup);
        if (scheduler.checkExists(triggerKey)) {
            String cron = "0 0 0 " + cycle + " * ?";
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(cron);
            CronTrigger cronTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
            cronTrigger = cronTrigger.getTriggerBuilder().withSchedule(scheduleBuilder).build();
            scheduler.rescheduleJob(triggerKey, cronTrigger);
            return true;
        }
        return false;
    }

    /**
     * 对trigger进行操作
     *
     * @param tool tool，trigger的名称和分组
     * @param type 触发器类型
     * @param type1     操作类型
     * @return 成功返回true，失败返回false
     */
    @Override
    public boolean handerTrigger(Tool tool, int type, String type1) {
        String triggerName;
        String triggerGroup;
        if (type == 1) {
            triggerName = String.valueOf(tool.gettDef().getWorkcell().getId());
            triggerGroup = String.valueOf(tool.getId());
        } else {
            triggerName = String.valueOf(tool.getId());
            triggerGroup = String.valueOf(tool.gettDef().getOwner().getId());
        }
        switch (type1) {
            case PAUSE:
                return triggerService.pauseTrigger(triggerName, triggerGroup);
            case RESUME:
                return triggerService.resumeTrigger(triggerName, triggerGroup);
            case REMOVE:
                return triggerService.removeTrigger(triggerName, triggerGroup);
            default:
                return false;
        }
    }

    /**
     * 启动所有定时任务
     */
    @Override
    public void startAllJobs() {
        try {
            scheduler.start();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭所有定时任务
     */
    @Override
    public void shutdownAllJobs() {
        try {
            if (!scheduler.isShutdown()) {
                scheduler.shutdown();
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
